package com.xln.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xln.dao.CategoryMapper;
import com.xln.pojo.Article;
import com.xln.pojo.Category;
import com.xln.service.ArticleService;
import com.xln.service.CategoryService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Resource
    private ArticleService articleService;
    @Override
    public List<Category> getCategoryTree() {
        // 获取所有分类
        List<Category> allCategories = this.list();
        
        // 构建树形结构
        return allCategories.stream()
                .filter(category -> category.getParentId() == 0)
                .peek(category -> category.setChildren(getChildren(category.getId(), allCategories)))
                .collect(Collectors.toList());
    }


    
    @Override
    public List<Category> getTopCategories() {
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", 0);
        queryWrapper.orderByAsc("order_num");
        return this.list(queryWrapper);
    }
    
    @Override
    public List<Category> getChildrenByParentId(Long parentId) {
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", parentId);
        queryWrapper.orderByAsc("order_num");
        return this.list(queryWrapper);
    }

//    获取指定分类ID的所有子分类ID（包括指定分类ID）

    @Override
    public List<Long> getChildIdsTree(Long id) {

        List<Category> allCategories = this.list();

        // 构建树形结构
        List<Category> categories = allCategories.stream()
                .filter(category -> category.getId() == id)
                .peek(category -> category.setChildren(getChildren(id, allCategories)))
                .collect(Collectors.toList());
        Category categoryTree = categories.get(0);

        List<Long> childIds = new ArrayList<>();
        childIds.add(categoryTree.getId());
        categoryTree.getChildren().forEach(child1 -> {

            if (child1.getChildren() != null) {
                child1.getChildren().forEach(child2 -> {
                    childIds.add(child2.getId());
                });
            }

            childIds.add(child1.getId());
        });

        return childIds;
    }

    @Transactional
    @Override
    public Boolean deleteCategoryAndChildAndArticles(Long id) {

//        获取子分类ID树（包括该分类ID）
        List<Long> childIdsTree = getChildIdsTree(id);
//         删除分类下所有的文章
        boolean ArtResult = articleService.remove(Wrappers.<Article>lambdaQuery().in(Article::getCategoryId, childIdsTree));
//         删除所有分类
        boolean CatResult  = this.removeByIds(childIdsTree);
        if (!ArtResult || !CatResult){
            return false;
        }
        return true;
    }

    @Transactional
    @Override
    public Boolean deleteCategoryAndChild(Long id) {
//        获取子分类ID树（包括该分类ID）
        List<Long> childIdsTree = getChildIdsTree(id);
        //         修改分类下所有的文章为未分类11
        boolean ArtResult = articleService.update(Wrappers.<Article>lambdaUpdate()
                .set(Article::getCategoryId, 11L)
                .in(Article::getCategoryId, childIdsTree));
        boolean CatResult  = this.removeByIds(childIdsTree);
//         删除所有分类
        if (!ArtResult || !CatResult){
            return false;
        }
        return true;
    }

    private List<Category> getChildren(Long parentId, List<Category> allCategories) {
        return allCategories.stream()
                .filter(category -> category.getParentId().equals(parentId))
                .peek(category -> category.setChildren(getChildren(category.getId(), allCategories)))
                .collect(Collectors.toList());
    }
}
